package com.xrit.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.pojo.User;
import com.xrit.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 登录认证与授权
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //1.通过用户名查询数据库
        User byName = userService.findByName(s);
        if (byName!=null){
            List<GrantedAuthority> list=new ArrayList<>();
            //2.认证与授权
            if (byName.getRoles()!=null && byName.getRoles().size()>0){
                byName.getRoles().forEach(r->{
                    //保存角色
                    list.add(new SimpleGrantedAuthority(r.getKeyword()));
                    //权限
                    if (r.getPermissions()!=null && r.getPermissions().size()>0){
                        r.getPermissions().forEach(p->{
                            list.add(new SimpleGrantedAuthority(p.getKeyword()));
                        });
                    }
                });
            }
            org.springframework.security.core.userdetails.User user=new org.springframework.security.core.userdetails.User(s,byName.getPassword(),list);
            return user;
        }
        return null;
    }
}
